package org.luckyjourney.config;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/**
 * @creator: liRong
 * @date: 2025/6/26 11:26
 */
@Configuration
@EnableRabbit // 启用RabbitMQ，这样Spring会扫描带有@RabbitListener注解的方法
public class RabbitMQConfig {

    // 聚合交换机
    @Bean
    public TopicExchange modelAggregationExchange() {
        return new TopicExchange("model.aggregation.exchange");
    }

    // 聚合队列
    @Bean
    public Queue modelAggregationQueue() {
        return QueueBuilder.durable("model.aggregation.queue")
                .withArgument("x-dead-letter-exchange" , "dlx-exchange")
                .build();
    }

    // 绑定
    @Bean
    public Binding modelAggregationBinding() {
        return BindingBuilder.bind(modelAggregationQueue())
                .to(modelAggregationExchange())
                .with("model.aggregation.routingKey"); // 路由键
    }

    // 死信交换机
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange("dlx.exchange");
    }

    // 死信队列
    @Bean
    public Queue dlxQueue() {
        return new Queue("dlx.queue" , true);
    }

    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue())
                .to(dlxExchange())
                .with("dlx.routingKey");
    }

    // JSON 消息转换器
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 启用类型信息
        objectMapper.activateDefaultTyping(
                objectMapper.getPolymorphicTypeValidator(),
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
